import columns from '@/config/columns'
// api
import {uploadImage} from '@/api/item'
import {searchModel, getModel, deleteModel, updateModel, addModel} from '@/api/model'
import {ignore} from '@/api/notification'
// utils
import {l2o, tableToExcel} from '@/utils'
// config
import config from '@/config'

import swal from 'sweetalert'

export const lifeHookMixin = {
    created() {
        this.model = this.$route.name
        this.defaultColumns = columns[this.model]
    },
    activated() {
        this.fetch()
    },
    mounted() {
        this.getFilters()
    },

}

export const itemMixin = {
    data() {
        return {
            tableLoading: false,
            showModal: false,
            data: [],
            opt: {},
            rawFilter: {},
            extendedFilter: {},
            orderBy: '',
            page: 1,
            pageCount: 0,
            pageSize: 50,
            total: 0,
            action: 'edit',
            item: null,
            itemID: null,
            filters: [],
            noteName: '',
            isRemoveDuplicate: false,
        }
    },
    methods: {
        // 根据columns配置获取可以过滤的字段
        getFilters() {
            // get filters
            this.defaultColumns.forEach(item => {
                if (item.filter) {
                    let filter = {
                        label: item.label,
                        value: item.filterKey ? item.filterKey : item.key,
                        inputType: item.filterInputType ? item.filterInputType : 'text',
                        options: item.filterOptions ? item.filterOptions : item.options,
                        searchable: item.hasOwnProperty("searchable") ? item.searchable : true,
                        rawFilter: item.rawFilter,
                        isRemoveDuplicate: item.isRemoveDuplicate
                    }

                    if (item.ajax) {
                        filter.ajax = item.ajax
                    }

                    if (item.defaultFilter) {
                        this.filters.unshift(filter)
                    } else {
                        this.filters.push(filter)
                    }
                }
            })
        },
        // 获取数据
        fetch(str) {
            if (!this.tableLoading) {
                this.tableLoading = true
                let opt = $.extend({}, this.opt, true)

                let params = {
                    search_keys: opt,
                    page: this.page,
                    order_by: this.orderBy,
                    page_size: this.pageSize,
                    raw_filter: this.rawFilter,
                    extended_filter: this.extendedFilter,
                }
                console.log("str...");
                searchModel(this.model, params).then(res => {
                    this.page = res.data.page.number
                    this.pageCount = res.data.page.range
                    this.total = res.data.page.total
                    this.data = this.isRemoveDuplicate ? this._removeDuplicateArr(res.data.list) : res.data.list
                    this.tableLoading = false
                  console.log("str success...");
                }).catch(e => {
                    this.tableLoading = false
                })
            }
        },
        // 去重
        _removeDuplicateArr(arr) {
            let newArr = []
            let tmp = {}
            arr.forEach( item => {
                if (!tmp[item.id]) {
                    tmp[item.id] = true
                    newArr.push(item)
                }
            } )
            return newArr
        },
        // 获取已选择的过滤条件
        filterFromLabel(filters) {
          console.log("filterFromLabel...");
          console.log(filters);
            this.opt = this.opt || {}
            filters.forEach( item => {
                this.opt[item.key] = item.value
            } )
            this.fetch("filterFromLabel")
        },
        // 弹框显示表格内容
        showTdDetail(msg) {
            msg = msg || ''
            swal('', msg, 'info')
        },
        // 点击排序
        sort(dir, column) {
            this.orderBy = dir[0] == 'descend' ? '-' + column[0] : column[0]
            this.fetch()
        },
        //
        upload(id, file) {
            let param = new FormData(); //创建form对象
            let extension = file.name.split('.')[1]
            param.append('file', file, id + '.' + extension) //通过append向form对象添加数据
            param.append('name', id)
            param.append('model', this.model)
            setTimeout(() => {
                uploadImage(param).then(res => {
                    this.fetch()
                })
            }, 1000)
        },
        // 点击触发过滤
        submit(conditions, flag, extendedFilter) {
            if (extendedFilter) {
                this.extendedFilter = extendedFilter
            } else {
                this.extendedFilter = {}
            }
            if (conditions && conditions.filters.length) {
                this.opt = {}
                this.rawFilter = {}
                conditions.filters.forEach(filter => {
                    if (filter.value !== '') {
                        if (filter.rawFilter) {
                            this.rawFilter[filter.column] = filter.value
                        } else {
                            this.opt[filter.column] = filter.value
                        }
                    }
                })
            } else {
                this.opt = {}
                this.rawFilter = {}
            }
            this.isRemoveDuplicate = flag
            this.fetch()
        },
        // 弹框显示添加item
        addItem() {
            this.action = 'add'
            this.itemID = null
            this.item = []
            for (let i = 0; i < this.defaultColumns.length; i++) {
                if (this.defaultColumns[i].add) {
                    //this.item.push(JSON.parse(JSON.stringify(this.defaultColumns[i])))
                    let tmp = {}
                    $.extend(true, tmp, this.defaultColumns[i])
                    this.item.push(tmp)
                }
            }
            this.showModal = true
        },
        // 弹框显示可编辑item
        editItem(props, newModel, columns) {
            if (!props.item.id) {
                return
            }
            this.action = 'edit'
            this.itemID = props.item.id
            this.tableLoading = true

            getModel(newModel ? newModel : this.model, null, {id: props.item.id}).then(res => {
                this.tableLoading = false
                this.origin = res.data.list[0]
                let item = []

                // only self okumasan order can edit
                let isOkumasn = false
                for (let key in this.origin) {
                    if (key === 'heyakun_order' && !this.origin['heyakun_order']) {
                        isOkumasn = true
                        break;
                    }
                }

                let defaultColumns = columns ? columns : this.defaultColumns
                // 根据columns配置过滤可以处理的字段
                for (let i = 0; i < defaultColumns.length; i++) {
                    let column = defaultColumns[i]
                    if (column.type !== 'actions' && column.type !== 'serial') {
                        let newItem = $.extend({}, column, true)
                        newItem.value = this.origin[column.key]
                        if (isOkumasn && column.key === 'checkout') {
                            newItem.edit = true
                        }
                        if (this.origin.is_locked) newItem.edit = false
                        item.push(newItem)
                    }
                }

                // 根据每个字段类型进行数据格式处理
                for (let i = 0; i < item.length; i++) {
                    if (item[i].inputType === 'select' && item[i].multiple) {
                        item[i].value = item[i].value && item[i].value.length > 0 ? item[i].value.split(';') : []
                    }

                    if (item[i].labelKey) {
                        item[i].defaultLabel = this.origin[item[i].labelKey]
                    }

                    if (item[i].inputType === 'reversecheckbox') {
                        item[i].value = !item[i].value
                    }

                    if (item[i].inputType === 'box') {
                        if (item[i].value) {
                            let arr = item[i].value.split(':')
                            if (arr.length > 1) {
                                let index = config.CONTACT_TOOLS.indexOf(arr[0])
                                if (index !== -1) {
                                    item[i].selectedVal = config.CONTACT_TOOLS[index]
                                    item[i].value = arr[1]
                                } else {
                                    item[i].selectedVal = 'other'
                                }

                            } else {
                                item[i].selectedVal = 'other'
                            }
                        }
                    }


                    if (item[i].inputType === 'money') {
                        item[i].currencyVal = this.origin[item[i].currencyKey]
                    }

                    if (item[i].inputType === 'datetime') {
                        item[i].value =  item[i].value ? item[i].value.split(' ')[0] : ''
                    }
                }

                this.item = item

                this.showModal = true
            }).catch(e => {
                this.tableLoading = false
            })
        },
        // 确认添加或修改某个item
        confirmSubmit(action, value, noRefresh) {
            let attr = l2o(value, 'key')
            if (attr && this.origin) {
                for (let key in attr) {
                    if (['checkin_time', 'checkout_time', 'flight_arrival_time', 'check_in_time', 'delivery_time'].indexOf(key) !== -1) {
                        let originUTCTime = moment(this.origin[key]).utc().format("YYYY-MM-DD HH:mm:ss")
                        if (originUTCTime === attr[key]) delete attr[key]
                    } else if (key === 'gentime' &&　this.origin[key] && attr[key] &&
                        this.origin[key].split(' ')[0] === attr[key].split(' ')[0]) {
                        delete attr[key]
                    } else if (this.origin[key] === attr[key] && action === 'edit') {
                        delete attr[key]
                    } else if (key === 'password' && attr[key] === '') {
                        delete attr[key]
                    }
                }
            }

            if (attr && attr.hasOwnProperty('actual_physical_room') && !attr.actual_physical_room) {
                attr.actual_physical_room = null
            }

            if (action === 'add') {
                swal({
                    title: "Are you sure?",
                    text: "Add this item",
                    icon: "warning",
                    dangerMode: true,
                    buttons: true,
                }).then((willAdd) => {
                    if (willAdd) {
                        this.tableLoading = true
                        addModel(this.model, attr).then(res => {
                            this.tableLoading = false
                            swal("success", "", "success").then(() => {
                                this.showModal = false
                            })
                            !noRefresh && this.fetch()
                        }).catch(e => {
                            this.tableLoading = false
                        })
                    }
                })
            } else if (action === 'edit') {
                this.tableLoading = true
                updateModel(this.model, this.itemID, attr).then(res => {
                    this.tableLoading = false
                    swal("success", "", "success").then(() => {
                        // this.showModal = false
                    })
                    !noRefresh && this.fetch()
                }).catch(e => {
                    this.tableLoading = false
                })
            }
        },
        // 点击删除某个item
        deleteItem(props) {
            if (props.item.id) {
                swal({
                    title: "Are you sure?",
                    text: "Remove this item",
                    icon: "warning",
                    dangerMode: true,
                    buttons: true,
                }).then((willDelete) => {
                    if (willDelete) {
                        this.tableLoading = true
                        deleteModel(this.model, props.item.id).then(res => {
                            this.tableLoading = false
                            swal("删除成功", "", "success")
                            this.fetch()
                        }).catch(e => {
                            this.tableLoading = false
                        })
                    }
                })
            }
        },
        // click ignore item
        ignoreItem(props) {
            if (props.item.id) {
                swal({
                    title: "Are you sure?",
                    text: "Ignore this item",
                    icon: "warning",
                    dangerMode: true,
                    buttons: true,
                }).then((will) => {
                    if (will) {
                        this.tableLoading = true
                        ignore(this.noteName, props.item.id, this.page, {}, 'seen').then(res => {
                            this.tableLoading = false
                            if (res.data.status === 'success') {
                                swal(res.data.status, "", "success")
                                this.fetch()
                            } else {
                                swal(res.data.status, "", "error")
                            }

                        }).catch(e => {
                            this.tableLoading = false
                        })
                    }
                })
            }
        },
        changePage(page) {
            this.page = page
            this.fetch()
        },
        genFee(fee, currency) {
            fee = fee || 0
            currency = currency || ''
            return `${currency} ${fee}`
        },
        exportExcel() {

            if (this.total > 2000) {
                return $.toast({
                    heading: '数据量太大，只可以导出2000以内的数据',
                    position: 'top-right',
                    loaderBg: '#ff6849',
                    icon: 'error',
                })
            }

            let headers = []
            for (let i=0; i<this.defaultColumns.length; i++) {
                let column = this.defaultColumns[i]
                if (column.type === 'actions' || column.type === 'serial') continue

                let type = 'String'
                if (column.inputType === 'number') {
                    type = 'Number'
                } else if (column.inputType === 'date') {
                    type = 'String'
                }
                headers.push({
                    label: column.label,
                    value: column.key,
                    type: type
                })
            }

            let params = {
                search_keys: this.opt,
                page: this.page,
                order_by: this.orderBy,
                page_size: 2000,
                raw_filter: this.rawFilter,
                extended_filter: this.extendedFilter
            }
            this.tableLoading = true
            searchModel(this.model, params).then(res => {
                this.tableLoading = false
                tableToExcel(headers, res.data.list, this.model, this.model)
            }).catch(e => {
                this.tableLoading = false
            })
        },
    }
}

export const checkListMixin = {
    data() {
        return {
            checkItem: {},
            checkItemModal: false,
        }
    },
    methods: {
        checkList(props, model) {
            this.itemID = props.item.id
            this.checkItemModal = true
        },
        saveCheckItem(text) {
            updateModel('CheckList',this.checkItem.id, {
                'name': text
            }).then( res => {
                if (res.status === 204) {
                    this.checkItem.name = text
                }
            } )
        }
    }
}
